package golf.stockdata.framework.ability;

import golf.stockdata.framework.exception.AbilityInitializationException;
import golf.stockdata.framework.exception.ApplicationException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;

public class SimpleDatabaseAbility implements DatabaseAbility {
	
	private static Logger logger = Logger.getLogger(SimpleDatabaseAbility.class);
	
	private String driverClass;
	private String jdbcUrl;
	private String user;
	private String password;
	
	private Connection connection;

	public void initializeAbility(Properties props)
			throws AbilityInitializationException {
		
		logger.debug(">>> initializeAbility");
		
		driverClass = props.getProperty("driverClass");
		if(driverClass == null){
			 throw new AbilityInitializationException("driverClass is missing");
		}
		
		jdbcUrl = props.getProperty("jdbcUrl");
		if(jdbcUrl == null){
			 throw new AbilityInitializationException("jdbcUrl is missing");
		}
		
		user = props.getProperty("user");
		if(user == null){
			 throw new AbilityInitializationException("user is missing");
		}
		
		password = props.getProperty("password");
		if(password == null){
			 throw new AbilityInitializationException("password is missing");
		}
	
		logger.debug("<<< initializeAbility");
	}

	public Connection getConnection() throws ApplicationException {
		
		logger.debug(">>> getConnection");
		
		try {
			if(connection != null
					&& !connection.isClosed()){
			}else{
					Class.forName(driverClass).newInstance();
					connection = DriverManager.getConnection(jdbcUrl, user, password);
			}
		} catch (InstantiationException e) {
			logger.error(e);
			if(logger.isDebugEnabled()){
				e.printStackTrace();
			}
			throw new ApplicationException(e);
		} catch (IllegalAccessException e) {
			logger.error(e);
			if(logger.isDebugEnabled()){
				e.printStackTrace();
			}
			throw new ApplicationException(e);
		} catch (ClassNotFoundException e) {
			logger.error(e);
			if(logger.isDebugEnabled()){
				e.printStackTrace();
			}
			throw new ApplicationException(e);
		} catch (SQLException e) {
			logger.error(e);
			if(logger.isDebugEnabled()){
				e.printStackTrace();
			}
			throw new ApplicationException(e);
		}
		
		logger.debug("<<< getConnection");
		return connection;
		
	}

	public void close(Connection conn) {
		
		logger.debug(">>> close");
		
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				logger.warn(e);
				if(logger.isDebugEnabled()){
					e.printStackTrace();
				}
			}
		}
		
		logger.debug("<<< close");
	}

	public boolean isPooled() {
		return false;
	}

}
